##################################################################################################################### 
# Name: Asylum Download and UI script
# Version: 0.0.1
# By: Ian "Inc" Caldwell
# Purpose: Make svn builds of Songbird on linux easier
# Contact me: Inc@inc-corporate.org
# License: BSD
#-------------------------------------------------------------------------------------------------------------------
# Copyright (c) 2006, Ian Caldwell (Inc-corporate.org)
# All rights reserved.
#-------------------------------------------------------------------------------------------------------------------
# todo: See readme.txt
# Special thanks to: The people at #python at irc.freenode.net for their advice, Michael Vandenberghe for his 
# help. Also thanks to Aali for hosting the svn! oh and also Rob Zinkov for his help. oh and thanks kbrooks.
# comments / suggestions / help welcome at Inc@inc-corporate.org THANKS!
####################################################################################################################
import os.path, urllib2, sys
# ui Section
errors = []
class ui:
        """
                The interface to the frontend, whatever code utilizes this module should follow this interface.
                This class will allow the backend, to communicate progress/data to the frontend.
                The default frontend provided here, is a command line front end.
        """
	progress=0
	def downloadProgress(self,progress, status, filename, size):
                if status == 0:
                        sys.stdout.write("  Downloading file: '"+filename+"' "+str(size)+"\n\t% 000")
                        sys.stdout.flush()
                elif status==1:
                        if progress > 0:
                                sys.stdout.write("\b\b\b")
                                sys.stdout.write( "%03i" % progress)
                                sys.stdout.flush()
                elif status==2:
                        sys.stdout.write("\b\b\b")
                        print "100"
                        print "   [Finished]\n"
                        sys.stdout.flush()
                elif status==-1:
                        print "\n  Download failed!"
                        sys.stdout.flush()
                return True
# download section
def download(urls,filename,ui):
        """
                Downloads file, it will try all the urls untill one works.
        """

        if os.path.exists(filename):
                print "Error file already exists"
                return True

        chunkSize=1024*8
        succeeded=False
        for url in urls:
                try:
                        opener = urllib2.build_opener()
                        opener.addheaders = [('User-agent', 'Asylum dependencies')]
                        u=opener.open(url)
                        totalSize = float(u.headers['content-length'])

                        sizeString = "%.2f Bytes" % (totalSize * 1.00)
                        if totalSize > 1024:
                                sizeString = "%.2f Kb" % (totalSize/1024.00)
                        if totalSize > (1048576):
                                sizeString = "%.2f Mb" % (totalSize/1048576.00)
                        if totalSize > (1073741824):
                                sizeString = "%.2f Gb ahh!" % (totalSize/1073741824.00)

                        if not ui.downloadProgress(0, 0, filename,sizeString):
                                return False

                        if totalSize > 0:
                                f=open(filename,'w')
                                current=0

                                while current <= totalSize:
                                        f.write(u.read(chunkSize))
                                        if not ui.downloadProgress(int(100.00*(current/totalSize)), 1, file,totalSize):
                                                return False
                                        current+=chunkSize
                                if not ui.downloadProgress(0, 2, file,totalSize):
                                        return False

                                f.close()

                        u.close()
                        succeeded=True
                        break

                except urllib2.HTTPError, e:
                        if not ui.downloadProgress(0, -1, filename,0):
                                return False
                        if e.code == 404:
                                errors.append("download error: '"+url+"' not found ( 404 ).")
                        elif e.code == 403:
                                errors.append("download error: Cannot access '"+url+"', permission denied ( 403 )")
                        else:
                                errors.append("urlib2 error: "+e.code)

        return succeeded